import React, {useEffect, useState} from 'react';
import {Layout,Tabs} from "antd";
import {
    Outlet, useLocation, useNavigate
} from "react-router-dom";
import {useAppTilte} from "@/hooks";

const {Content} = Layout;
const { TabPane } = Tabs;
function IndexContent() {
    const location = useLocation();
    const navigate = useNavigate();
    type TPanes = {
        title:string,
        key:string,
        closable:boolean
    }
    const [panes,setPanes] = useState<TPanes[]>([
        {
            title:"主页",
            key:"/",
            closable:false
        }
    ])
    const titleObj = useAppTilte();
    useEffect(()=>{
        const info:TPanes = panes.find((v:TPanes)=>v.key === location.pathname) as TPanes;
        if(!info){
            setPanes([
                ...panes,
                {
                    title:titleObj.subTitle,
                    key:location.pathname,
                    closable: true
                }
            ])
        }

    },[location.pathname])

    return (
        <Content style={{margin: '5PX'}}>
            <div className="site-layout-background" style={{padding: 5, height:"100%"}}>

                <Tabs type="editable-card"
                      hideAdd={true}
                      // 切换面板的回调
                      onChange={(activeKey)=>{
                          navigate(activeKey);
                      }}
                      // 当前激活 tab 面板的 key
                      activeKey={location.pathname}
                      //新增和删除页签的回调，在 type="editable-card" 时有效
                      onEdit={(actionKey,action )=>{
                          if(action === "remove"){
                              // setPanes(panes.filter((v:TPanes)=>v.key !== actionKey))
                              const copyPanes = [...panes];
                              const index:number = copyPanes.findIndex((v:TPanes)=>v.key === actionKey) as number;
                              copyPanes.splice(index,1);
                              setPanes(copyPanes);
                              navigate(copyPanes[index-1].key)
                          }
                      }}
                >
                    {panes.map(pane => (
                        <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                            <Outlet/>
                        </TabPane>
                    ))}
                </Tabs>
            </div>
        </Content>
    );
}

export default IndexContent;